package com.njy.aop.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 互斥锁练习
 */
public class huchiLock {
    //定义可重入锁
    private  static Lock lock =  new ReentrantLock();
    public List<String > test(){
        List<String> result = new ArrayList();
        result = getDataForCache();
        if(result.isEmpty()){
            try {
                if(lock.tryLock()){
                    System.out.println("我获取了锁");
                    //从数据查数据
                    //放入缓存
                }
            }finally {
                lock.unlock();
            }

        }else{
            //再次从缓存中查
            result = getDataForCache();
            if(result.isEmpty()){
                try {
                    System.out.println("没拿到锁，缓存中也没有数据，歇一会在获取锁");
                    Thread.sleep(5000);
                    return test();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    /**
     * 模拟从缓存中获取数据
     * @return
     */
    private List getDataForCache() {
        List<String> re = new ArrayList<>();
        return re;
    }
}
